package com.maxbill.hive.main;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.maxbill.hive.util.JdbcUtils;

/**
 * @user maxbill
 * @date 2018/01/16
 * @func hive操作测试类
 */
public class HiveTest {

	public static void main(String[] args) {
		// String sql = "drop table tb_test";
		// runHandleSql(sql);
		runQuerySql("show tables");
	}

	// 数据操作
	public static void runHandleSql(String sql) {
		try {
			Connection conn = JdbcUtils.openConnection();
			Statement stmt = conn.createStatement();
			if (null != stmt) {
				System.out.println(">>>>>>>>>>>>>>>>>>>>:打开连接成功...");
				stmt.execute(sql);
				// 调用关闭方法释放连接
				JdbcUtils.closeConnection(stmt, conn);
			} else {
				System.out.println(">>>>>>>>>>>>>>>>>>>>:打开连接失败...");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 查询数据
	public static void runQuerySql(String sql) {
		try {
			Connection conn = JdbcUtils.openConnection();
			Statement stmt = conn.createStatement();
			if (null != stmt) {
				System.out.println(">>>>>>>>>>>>>>>>>>>>:打开连接成功...");
				ResultSet rs = stmt.executeQuery(sql);
				System.out.println(">>>>>>>>>>>>>>>>>>>>:执行运行结果...");
				// 输出查询的结果集
				List list = resultSetToList(rs);
				for (Object listObj : list) {
					System.err.println(listObj.toString());
				}
				// 调用关闭方法释放连接
				JdbcUtils.closeConnection(stmt, conn);
			} else {
				System.out.println(">>>>>>>>>>>>>>>>>>>>:打开连接失败...");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void testHiveConn() {
		try {
			Connection conn = JdbcUtils.openConnection();
			Statement stmt = conn.createStatement();
			if (null != stmt) {
				System.out.println(">>>>>>>>>>>>>>>>>>>>:打开连接成功...");
				// 此处主要是测试连接是否正常，打开成功后，我们调用关闭方法释放连接
				JdbcUtils.closeConnection(stmt, conn);
			} else {
				System.out.println(">>>>>>>>>>>>>>>>>>>>:打开连接失败...");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// ResultSet结果集转成list
	public static List resultSetToList(ResultSet rs) throws java.sql.SQLException {
		if (rs == null)
			return Collections.EMPTY_LIST;
		ResultSetMetaData md = rs.getMetaData(); // 得到结果集结构信息，比如字段数、字段名等
		int columnCount = md.getColumnCount(); // ResultSet的列数
		List list = new ArrayList();
		Map rowData = new HashMap();
		while (rs.next()) {
			rowData = new HashMap(columnCount);
			for (int i = 1; i <= columnCount; i++) {
				rowData.put(md.getColumnName(i), rs.getObject(i));
			}
			list.add(rowData);
		}
		return list;
	}

}
